package com.yxw.live_vod_backend_boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxw.live_vod_backend_boot.dto.VodDosageDto;
import com.yxw.live_vod_backend_boot.entity.YxVodDosageEntity;
import com.yxw.live_vod_backend_boot.mapper.VodDosageMapper;
import com.yxw.live_vod_backend_boot.service.VodBackendService;
import com.yxw.live_vod_backend_boot.util.UserUtil;
import com.yxw.live_vod_backend_boot.util.VolcanoEngineUtil;
import com.yxw.live_vod_backend_boot.vo.*;
import com.yxw.live_vod_backend_facade.dto.AddVodUsageInformationDto;
import com.yxw.live_vod_facade.dto.*;
import com.yxw.live_vod_facade.feign.OnDemandFeignClient;
import com.yxw.live_vod_facade.vo.OnDemandCommentVO;
import com.yxw.live_vod_facade.vo.PageVodInfoListVO;
import com.yxw.live_vod_facade.vo.VideoReviewVO;
import com.yxw.live_vod_facade.vo.VodSalesRevenueVo;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseDateTime;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author liuxin
 * @create 2023-12-1
 * @description 点播相关后台操作
 */
@Service
public class VodBackendServiceImpl implements VodBackendService {

    @Autowired
    private OnDemandFeignClient onDemandFeignClient;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private VodDosageMapper vodDosageMapper;

    @Autowired
    private VolcanoEngineUtil volcanoEngineUtil;

    /**
     * 视频审核处理
     * @param dto
     * @return
     */
    @Override
    public BaseResult handle(VideoReviewHandelDTO dto) {
       return  onDemandFeignClient.handle(dto);
    }

    /**
     * 查询待审核视频列表
     * @param dto
     * @return
     */
    @Override
    public BaseResult<PageVO<VideoReviewVO>> pageVideoReviews(PageVideoReviewsDTO dto) {
        return onDemandFeignClient.pageVideoReviews(dto);
    }

    /**
     * 店铺点播作品列表详情查询
     * @param dto
     * @return
     */
    @Override
    public BaseResult<PageVO<PageVodInfoListVO>> pageVodInfoList(PageVodInfoListDto dto) {
        return onDemandFeignClient.pageVodInfoList(dto);
    }

    /**
     * 查询视频下面的评论和回复
     * @param dto
     * @return
     */
    @Override
    public BaseResult<PageVO<OnDemandCommentVO>> pageVideoComments(PageOnDemandCommentDTO dto) {
        return onDemandFeignClient.pageVideoComments(dto);
    }

    /**
     * 删除评论
     * @param commentId
     * @return
     */
    @Override
    public BaseResult deleteCommentById(Long commentId) {
        return onDemandFeignClient.deleteCommentById(commentId);
    }

    /**
     * 下架视频
     * @param dto
     * @return
     */
    @Override
    public BaseResult deleteVideoByIds(VideoDeleteDTO dto) {
        dto.setUserId(userUtil.getLoginUserId());
        dto.setUserName(userUtil.getLoginName());
        return onDemandFeignClient.deleteVideoByIds(dto);
    }

    /**获取点播视频用量信息
     * @param dto
     * @return
     */
    @Override
    public List<VodDosageVo> getVodUsageInformation(VodDosageDto dto) {
        List<VodDosageVo> voList = new ArrayList<>();
        //手动统计
        if(null!=dto.getExeDate()){
            AddVodUsageInformationDto usageDto=new AddVodUsageInformationDto();
            usageDto.setExeDate(dto.getExeDate());
            insertVodUsageInformationByDay(usageDto);
        }else {
            if ((null == dto.getTimeStart() && null != dto.getTimeEnd()) || (null != dto.getTimeStart() && null == dto.getTimeEnd())) {
                throw new BaseException("开始时间和结束时间必须同时有值才能进行查询");
            }
            if (null != dto.getTimeEnd() && dto.getTimeEnd().compareTo(new Date()) > 0) {
                throw new BaseException("结束查询时间不能大于当前时间");
            }
            LambdaQueryWrapper<YxVodDosageEntity> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.orderByDesc(YxVodDosageEntity::getDayTime);
            //有时间范围不进行分页
            if (null != dto.getTimeStart()) {
                queryWrapper.ge(YxVodDosageEntity::getDayTime, dto.getTimeStart());
                queryWrapper.le(YxVodDosageEntity::getDayTime, dto.getTimeEnd());
                List<YxVodDosageEntity> yxVodDosageEntities = vodDosageMapper.selectList(queryWrapper);
                if (null != yxVodDosageEntities && !yxVodDosageEntities.isEmpty()) {
                    voList = BeanUtil.copyToList(yxVodDosageEntities, VodDosageVo.class);
                }
            } else {
                //默认查询七条
                Page<YxVodDosageEntity> page = new Page<>(0, 7);
                Page<YxVodDosageEntity> entityPage = vodDosageMapper.selectPage(page, queryWrapper);
                List<YxVodDosageEntity> records = entityPage.getRecords();
                if (null != records && !records.isEmpty()) {
                    voList = BeanUtil.copyToList(records, VodDosageVo.class);
                }
            }
        }
        return voList;
    }

    /**
     * 定时任务查询点播视频用量（天维度）
     * queryData:查询时间 用于补偿使用 yyyy-MM-dd 格式
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertVodUsageInformationByDay(AddVodUsageInformationDto dto) {
        LambdaQueryWrapper<YxVodDosageEntity> queryWrapper=new LambdaQueryWrapper();
        //查询日期
        String dataStr="";
        Date data=null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        //定时任务执行
        if(null==dto.getExeDate()){
            //昨天时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-1);
            dataStr = formatter.format(calendar.getTime());
            data = BaseDateTime.getDate(dataStr);
        }else{//手动执行
            dataStr= formatter.format(dto.getExeDate());
            data=BaseDateTime.getDate(dataStr);
        }
        queryWrapper.eq(YxVodDosageEntity::getDayTime,data);
        YxVodDosageEntity entity = vodDosageMapper.selectOne(queryWrapper);
        if(null==entity){
            entity=new YxVodDosageEntity();
            entity.setDayTime(data);
        }
        //查询时间范围
        Date startTime = BaseDateTime.getDate(dataStr+" 00:00:00");
        Date endTime = BaseDateTime.getDate(dataStr+" 23:59:59");
        //查询带宽用量
        VodBandwidthDataVo vandwidthVo=volcanoEngineUtil.describeVodDomainBandwidthData(startTime,endTime);
        entity.setBandWidth(BigDecimal.valueOf(vandwidthVo.getPeakBandwidth()));
        //查询流量用量
        VodTrafficDataVo trafficDataVo=volcanoEngineUtil.describeVodDomainTrafficData(startTime,endTime);
        entity.setTraffic(BigDecimal.valueOf(trafficDataVo.getTotalTraffic()));
        //查询存储用量
        VodStorageDataVo storageDataVo=volcanoEngineUtil.describeVodSpaceStorageData(startTime,endTime);
        entity.setStorage(BigDecimal.valueOf(storageDataVo.getStorage()));
        //查询转码用量
        VodTranscodeDataVo transcodeDataVo=volcanoEngineUtil.describeVodSpaceTranscodeData(startTime,endTime);
        entity.setTransDuration(BigDecimal.valueOf(transcodeDataVo.getTransDuration()));
        if(null!=entity.getDosageId()){
            entity.setUpdateTime(new Date());
            vodDosageMapper.updateById(entity);
        }else{
            entity.setCreateTime(new Date());
            vodDosageMapper.insert(entity);
        }
    }

    /**
     * 查询点播概览信息
     * @return
     */
    @Override
    public VodOverviewVo getVodOverviewInfo() {
        //查询昨天的月份
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-1);
        String month = formatter.format(calendar.getTime());
        //查询月用量统计
        VodOverviewVo vo =vodDosageMapper.getVodOverviewByMonth(month);
        //查询七天内用量信息
        VodDosageDto dto=new VodDosageDto();
        List<VodDosageVo> voList = this.getVodUsageInformation(dto);
        vo.setDosagList(voList);
        return vo;
    }

    /**
     * 查询点播商品带货收入详情
     * @param videoId
     * @return
     */
    @Override
    public BaseResult<VodSalesRevenueVo> getVodSalesRevenue(Long videoId) {
        return onDemandFeignClient.getVodProductOrderByVideoId(videoId);
    }
}
